package com.yumeng.framework.auth.security.configurers;

import com.yumeng.framework.auth.security.authentication.captcha.CaptchaVerifyFilter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wxd
 * @date 2025/4/2 13:42
 */
public final class CaptchaVerifyConfigurer extends AbstractHttpConfigurer<CaptchaVerifyConfigurer, HttpSecurity> {

    private CaptchaVerifyFilter filter;
    private AuthenticationFailureHandler failureHandler;

    public CaptchaVerifyConfigurer(CaptchaVerifyFilter filter) {
        this.filter = filter;
    }

    public CaptchaVerifyConfigurer captchaParameter(String captchaParameter) {
        this.filter.setCaptchaParameter(captchaParameter);
        return this;
    }

    public CaptchaVerifyConfigurer captchaIdParameter(String captchaIdParameter) {
        this.filter.setCaptchaIdParameter(captchaIdParameter);
        return this;
    }

/*    public CaptchaVerifyConfigurer failureHandler(AuthenticationFailureHandler failureHandler) {
        this.filter.setFailureHandler(failureHandler);
        return this;
    }*/

    public CaptchaVerifyConfigurer captchaVerifyUrls(List<String> captchaVerifyUrls) {
        if (CollectionUtils.isNotEmpty(captchaVerifyUrls)){
            List<RequestMatcher> requestMatchers = new ArrayList<>();
            for (String url : captchaVerifyUrls){
                requestMatchers.add(PathPatternRequestMatcher.withDefaults().matcher(url));
            }
            this.filter.setRequiresRequestMatcher(new OrRequestMatcher(requestMatchers));
        }
        return this;
    }

    @Override
    public void init(HttpSecurity builder) throws Exception {
    }

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        builder.addFilterAfter(this.filter, AbstractPreAuthenticatedProcessingFilter.class);
    }

    public static CaptchaVerifyConfigurer captchaVerify(){
        CaptchaVerifyFilter filter = new CaptchaVerifyFilter();
        return new CaptchaVerifyConfigurer(filter);
    }
}
